package site.syksy.qingzhou.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.vote.UnanimousBased;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import site.syksy.qingzhou.security.authentication.GeneralLogoutSuccessHandler;
import site.syksy.qingzhou.security.authorization.GeneralAccessDecisionVoter;
import site.syksy.qingzhou.security.authorization.GeneralAccessDeniedHandler;
import site.syksy.qingzhou.security.authorization.GeneralAuthenticationEntryPoint;
import site.syksy.qingzhou.upms.service.UserService;

import java.util.Arrays;
import java.util.List;

import static site.syksy.qingzhou.security.authentication.GeneralAuthenticationDsl.generalDsl;

/**
 * @author Raspberry
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    GeneralAccessDecisionVoter generalAccessDecisionVoter;

    @Autowired
    UserService userService;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .accessDecisionManager(accessDecisionManager())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new GeneralAuthenticationEntryPoint())
                .accessDeniedHandler(new GeneralAccessDeniedHandler())
                .and()
                .apply(generalDsl())
                .setLoginUrl("/qz/api/login/account").setUserService(userService)
                .and()
                .logout().logoutUrl("/qz/api/login/outLogin").logoutSuccessHandler(new GeneralLogoutSuccessHandler());
        http.sessionManagement().maximumSessions(1).expiredUrl("/qz/api/login/account").maxSessionsPreventsLogin(true);
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(
                "/",
                "/swagger-ui.html",
                "/v3/api-docs/**",
                "/swagger-ui/**",
                "/h2-console/**",
                "/qz-ui/**"
                );
    }

    @Bean
    public AccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters
                = Arrays.asList(generalAccessDecisionVoter);
        AccessDecisionManager accessDecisionManager = new UnanimousBased(decisionVoters);
        return accessDecisionManager;
    }

}
